﻿using System;
using System.Linq;
using Microsoft.SharePoint;

namespace RGB.SharePoint.SPBlockFileTypes
{
    public class BlockFileTypesEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdding(SPItemEventProperties properties)
        {
            try
            {
                SPList list = properties.List;
                if (list.RootFolder.Properties.ContainsKey(Constants.BLOCK_TYPE_PROPERTY)
                    && list.RootFolder.Properties.ContainsKey(Constants.EXTENSIONS_LIST_PROPERTY))
                {
                    BlockType blockType = (BlockType)Enum.Parse(typeof(BlockType), list.RootFolder.Properties[Constants.BLOCK_TYPE_PROPERTY].ToString());
                    string extensionsList = list.RootFolder.Properties[Constants.EXTENSIONS_LIST_PROPERTY].ToString();
                    string[] extensions = extensionsList.Split(new char[] { ',' });
                    string fileName = properties.BeforeUrl;
                    string extension = fileName.Substring(fileName.LastIndexOf('.') + 1);
                    if (list is SPDocumentLibrary)
                    {
                        bool block = false;
                        switch (blockType)
                        {
                            case BlockType.Allow:
                                if (!extensions.OfType<string>().Contains(extension))
                                {
                                    block = true;
                                }
                                break;
                            case BlockType.Block:
                                if (extensions.Contains(extension))
                                {
                                    block = true;
                                }
                                break;
                        }
                        if (block)
                        {
                            properties.Cancel = true;
                            properties.ErrorMessage = extension + " files are blocked by adminstrator for this library.";
                            properties.Status = SPEventReceiverStatus.CancelWithError;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Do nothing                
            }
        }
    }
}
